package com.lw.leetcode.arr.b;

/**
 * 529. 扫雷游戏
 *
 * @Author liw
 * @Date 2021/6/24 17:30
 * @Version 1.0
 */
public class UpdateBoard {

    private char[][] board;
    private int a;
    private int b;

    public char[][] updateBoard(char[][] board, int[] click) {
        this.board = board;
        a = board.length;
        b = board[0].length;

        int x = click[0];
        int y = click[1];

        if (board[x][y] == 'M') {
            board[x][y] = 'X';
            return board;
        }
        find(x, y);
        return board;
    }

    private void find(int x, int y) {
        if (x < 0 || y < 0 || x == a || y == b) {
            return;
        }
        char v = board[x][y];
        if (v == 'M') {
            return;
        }
        if (v == 'E') {
            int sum = 0;
            sum += check(x - 1, y);
            sum += check(x + 1, y);
            sum += check(x, y - 1);
            sum += check(x, y + 1);
            sum += check(x - 1, y - 1);
            sum += check(x + 1, y + 1);
            sum += check(x + 1, y - 1);
            sum += check(x - 1, y + 1);
            if (sum != 0) {
                board[x][y] = (char) (sum + 48);
                return;
            }
            board[x][y] = 'B';
            find(x - 1, y);
            find(x + 1, y);
            find(x, y - 1);
            find(x, y + 1);
            find(x - 1, y - 1);
            find(x + 1, y + 1);
            find(x + 1, y - 1);
            find(x - 1, y + 1);
        }
    }

    private int check(int x, int y) {
        if (x < 0 || y < 0 || x == a || y == b) {
            return 0;
        }
        char v = board[x][y];
        if (v == 'M') {
            return 1;
        }
        return 0;
    }

}
